import React, { useEffect, useState, useCallback } from 'react';
import axios from 'axios';

export const request = async url => {
  const resp = await axios.get(url);
  const data = resp.data;
  if (data.code !== 200 || data.code !== 0) {
    alert('服务器开小差了');
    return {};
  }
  return data.data;
};

const useUser = id => {
  const [user, setUser] = useState({});
  const [loading, setLoading] = useState(false);
  const getUser = async () => {
    setLoading(true);
    const user = await request(`https://xiaozhu.run/api/user/${id}`);
    setLoading(false);
    setUser(user);
  };
  useEffect(() => {
    getUser();
  }, [id]);
  return [user, loading];
};

// @todo 大家自行实现
const useFetch = (url, options, dependencies) => {};

const GetUser = () => {
  const [id, setId] = useState(9527);

  const [user, loading] = useUser(id);
  return (
    <div>
      <button onClick={() => setId(id + 1)}>Get User {id}</button>
      {loading && <span>Loading...</span>}
      <div>EmailA: {user.email}</div>
      <div>NameA: {user.username}</div>
    </div>
  );
};

// 嵌套情况
const Parent = props => {
  console.log(props.children);
  // userState();
  return (
    <div>
      {<props.header />}我是老大 <br /> {props.children}
    </div>
  );
};

export default () => {
  class Header extends React.Component {
    render() {
      return <h3>头部111</h3>;
    }
  }
  return (
    <Parent header={Header}>
      <GetUser />
      <GetUser />
    </Parent>
  );
};
